/**
 * @Title: LoginSyncLogic.java
 * @Package: com.jason.fingerprint.logic
 * @Descripton: 登录
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月25日 下午4:13:11
 * @Version: V1.0
 */
package com.jason.fingerprint.logic;

import java.util.List;

import org.kymjs.aframe.http.HttpCallBack;
import org.kymjs.aframe.http.KJFileParams;
import org.kymjs.aframe.http.KJHttp;
import org.kymjs.aframe.utils.StringUtils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android_serialport_api.FingerprintManager;
import android_serialport_api.FingerprintReader;
import android_serialport_api.FingerprintReader.OnDownCharListener;
import android_serialport_api.FingerprintReader.OnStoreCharListener;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.AppGlobal;
import com.jason.fingerprint.beans.LoginReq;
import com.jason.fingerprint.beans.LoginResp;
import com.jason.fingerprint.beans.UserBean;
import com.jason.fingerprint.beans.ui.FingerPrintBean;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.utils.CodecUtils;

/**
 * @ClassName: LoginSyncLogic
 * @Description: 登录
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年10月25日 下午4:13:11
 */
public class LoginSyncLogic extends Logic {

	public static final int LOGIN_FINGERPRINT = 1;// 指纹登录
	public static final int LOGIN_ACCOUNT = 2;// 账号登录

	private static final String TAG = "LoginSyncLogic";

	private Handler mHandler;
	private boolean mIsCallBack;// 是否有回调，此需要Handle
	private int mCurrentIndex = 1;// 当前页
	private Message mMessage;
	private Context mContext;
	private LoginReq mLoginReq;// 请求参数
	private int mType;
	private FingerprintReader mAsyncFingerprint;
	private int mFingerId = 0;
	private int mFingerCount = 0;
	private int mFingerCurrent = -1;
	private List<FingerPrintBean> mFingerPrintBeans;
	private List<UserBean> values;
	private int totalRowsCount;

	public LoginSyncLogic() {

	}

	public LoginSyncLogic(AppContext appContext, Context context,
			Handler handler, boolean isCallBack, LoginReq loginReq) {
		super(appContext);
		this.mHandler = handler;
		this.mContext = context;
		this.mMessage = new Message();
		this.mIsCallBack = isCallBack;
		this.mLoginReq = loginReq;
		initAsyncFingerprint();
	}

	private void initAsyncFingerprint() {
		mAsyncFingerprint = FingerprintManager.getInstance().getNewAsyncFingerprint();
		mAsyncFingerprint.PS_Empty();
		mFingerId = 0;
		if (mAsyncFingerprint == null) return;
		mAsyncFingerprint.setOnDownCharListener(new OnDownCharListener() {

			@Override
			public void onDownCharSuccess() {
				Log.i(TAG, "setOnDownCharListener onDownCharSuccess mFingerId:"
						+ mFingerId);
				mAsyncFingerprint.PS_StoreChar(2, mFingerId);
			}

			@Override
			public void onDownCharFail() {
				Log.i(TAG, "setOnDownCharListener onDownCharFail mFingerId:"
						+ mFingerId);
				storeFinger();
			}
		});
		mAsyncFingerprint.setOnStoreCharListener(new OnStoreCharListener() {

			@Override
			public void onStoreCharSuccess() {
				Log.i(TAG,
						"setOnStoreCharListener onStoreCharSuccess mFingerId:"
								+ mFingerId);
				storeFinger();
			}

			@Override
			public void onStoreCharFail() {
				Log.i(TAG, "setOnStoreCharListener onStoreCharFail mFingerId:"
						+ mFingerId);
				storeFinger();
			}
		});
	}

	@Override
	public void execute() {
		Log.i(TAG, "execute");
		try {
			mAsyncFingerprint.PS_Empty();
			mKjdb.deleteTable(UserBean.class);
			mKjdb.deleteTable(FingerPrintBean.class);
		} catch (Exception e) {
		}
		datbLoginSync();
	}

	@Override
	public void send() {
		if (mIsCallBack) {
			mHandler.sendMessage(mMessage);
			mMessage = new Message();
		}
	}

	// 档案同步
	private void datbLoginSync() {
		Log.i(TAG, "mLoginReq---->" + mLoginReq.toString());
		mType = mLoginReq.getType();
		String url = mLoginReq.getUrl();
		mParams = new KJFileParams();
		mParams.put("type", String.valueOf(mType));
		// 指纹登录
		mParams.put(AppGlobal.HTTP_PARAM_IMEI, mImei);
		if (mType == LOGIN_ACCOUNT) {
			// 账号登录
			mParams.put("loginName", mLoginReq.getLoginName());
			mParams.put("loginPwd", mLoginReq.getLoginPwd());
		}
		mParams.put(AppGlobal.HTTP_PARAM_CURRENTINDEX,
				String.valueOf(mCurrentIndex));
		
		Log.i(TAG, "----->API:" + url);
		Log.i(TAG, "----->API:" + mParams.getParamString());
		KJHttp kjHttp = new KJHttp();
		kjHttp.post(url, mParams, new HttpCallBack() {

			@Override
			public void onSuccess(Object arg0) {
				String result = CodecUtils.base64Decode(arg0.toString());
				Log.i(TAG, "----->Result:" + result);
				Gson gson = new GsonBuilder().create();
				LoginResp loginResp = gson.fromJson(result, LoginResp.class);
				if (loginResp != null && !loginResp.isEmpty()) {
					Log.i(TAG, loginResp.toString());
					values = loginResp.getValues();
					totalRowsCount = loginResp.getTotalRowsCount();
					if (values != null && !values.isEmpty()) {
						// 保存信息到数据库
						for (UserBean userBean : values) {
							// 保存工作人员信息
							if (userBean != null) {
								String userId = String.valueOf(userBean
										.getUserId());
								String userName = userBean.getUserName();
								String fp1 = userBean.getFingerprint1();
								String fp2 = userBean.getFingerprint2();
								mKjdb.save(userBean);
								// 保存工作人员指纹信息
								mKjdb.save(new FingerPrintBean(userId,
										userName, fp1, 2, 1));
								mKjdb.save(new FingerPrintBean(userId,
										userName, fp2, 2, 2));
							}
						}
						if (!loginResp.isLastPage()) {
							mCurrentIndex++;
							datbLoginSync();
						} else {
							saveFinger();
						}
					} else {
						mMessage.what = UIHelper.LOGIN_FAIL;
						mMessage.obj = loginResp.getRespMsg();
						send();
					}
				} else {
					mMessage.what = UIHelper.LOGIN_FAIL;
					mMessage.obj = "登录失败,请重新尝试";
					send();
				}
			}

			@Override
			public void onLoading(long arg0, long arg1) {

			}

			@Override
			public void onFailure(Throwable arg0, int arg1, String arg2) {
				Log.i(TAG, "onFailure " + arg0.getMessage() + ",arg1:" + arg1
						+ ",arg2:" + arg2);
				mMessage.what = UIHelper.LOGIN_FAIL;
				mMessage.obj = "登录失败,请重新尝试";
				send();
			}
		});
	}

	// 储存指纹信息到设备
	private synchronized void storeFinger() {
		if (mAsyncFingerprint != null) {
			mFingerCurrent++;
			FingerPrintBean bean = null;
			if (mFingerCurrent > -1 && mFingerCurrent < mFingerCount) {
				bean = mFingerPrintBeans.get(mFingerCurrent);
				if (bean != null && !StringUtils.isEmpty(bean.getFp())) {
					mFingerId = bean.getId();
					byte[] b = CodecUtils
							.base64DecodeToByte(bean.getFp());
					if (b != null) {
						mAsyncFingerprint.PS_DownChar(b);
					}else {
						storeFinger();
					}
				} else {
					storeFinger();
				}
			} else {
				mMessage.what = UIHelper.LOGIN_SUCCESS;
				mMessage.arg1 = totalRowsCount;
				mMessage.obj = values;
				send();
			}
		} else {
			mMessage.what = UIHelper.LOGIN_SUCCESS;
			mMessage.arg1 = totalRowsCount;
			mMessage.obj = values;
			send();
		}
	}

	private void saveFinger() {
		try {
			mFingerId = 0;
			mFingerCount = 0;
			mFingerCurrent = -1;
			mFingerPrintBeans = mKjdb.findAllByWhere(FingerPrintBean.class,
					"type = 2");
		} catch (Exception e) {
			mMessage.what = UIHelper.LOGIN_SUCCESS;
			mMessage.arg1 = totalRowsCount;
			mMessage.obj = values;
			send();
		}

		if (mFingerPrintBeans != null && !mFingerPrintBeans.isEmpty()) {
			mFingerCount = mFingerPrintBeans.size();
			storeFinger();
		}else {
			mMessage.what = UIHelper.LOGIN_SUCCESS;
			mMessage.arg1 = totalRowsCount;
			mMessage.obj = values;
			send();
		}
	}

	/* (non-Javadoc)
	 * @see com.jason.fingerprint.logic.Logic#destory()
	 */
	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	}

}
